package com.technician.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.technician.common.DeleteRequest;
import com.technician.common.ResponseResult;
import com.technician.exceptionHandler.GlobalSystemException;
import com.technician.model.dto.goods.GoodsInsertRequest;
import com.technician.model.dto.goods.GoodsQueryRequest;
import com.technician.model.dto.goods.GoodsUpdateRequest;
import com.technician.model.entity.Goods;
import com.technician.model.entity.GoodsType;
import com.technician.model.entity.User;
import com.technician.model.enums.HttpStatusEnum;
import com.technician.model.security.LoginUser;
import com.technician.model.vo.GoodsVO;
import com.technician.service.GoodsService;
import com.technician.service.GoodsTypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsTypeService goodsTypeService;

    /**
     * 新增一个商品（管理员）
     *
     * @param goodsInsertRequest
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:user:list')")
    public ResponseResult save(@RequestBody @Validated GoodsInsertRequest goodsInsertRequest) {

        // 获取登录用户
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = loginUser.getUser();

        Goods goods = new Goods();
        // 构造默认的标签和图片
        String[] tags = new String[]{"其他"};
        String[] images = new String[]{"https://ts2.cn.mm.bing.net/th?id=OIP-C.2TG_Vyb9szQcGK84NVDyLgHaHa&w=249&h=250&c=8&rs=1&qlt=90&o=6&dpr=1.3&pid=3.1&rm=2"};
        // 拷贝 分类名称和描述
        BeanUtils.copyProperties(goodsInsertRequest,goods);
        goods.setTags(Optional.ofNullable(goodsInsertRequest.getTags()).orElse(JSONUtil.toJsonStr(tags)));
        goods.setImages(Optional.ofNullable(goodsInsertRequest.getImages()).orElse(JSONUtil.toJsonStr(images)));
        goods.setCreateBy(user.getId());
        goods.setCreateTime(LocalDateTime.now());
        goods.setUpdateBy(user.getId());
        goods.setUpdateTime(LocalDateTime.now());

        // 查询商品分类存不存在
        GoodsType goodstype = goodsTypeService.getById(goods.getType());
        if (goodstype==null){
            throw new GlobalSystemException(400,"商品分类不存在");
        }

        // 插入
        boolean save = goodsService.save(goods);
        if (!save){
            throw new GlobalSystemException(400,"插入失败");
        }

        return ResponseResult.success("新建商品成功");
    }

    /**
     * 删除一个商品 （管理员）
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('system:user:list')")
    public ResponseResult<Boolean> deleteGoodsById(@RequestBody @Validated DeleteRequest deleteRequest) {
        boolean b = goodsService.removeById(deleteRequest.getId());
        if (!b){
            return ResponseResult.error(400,"删除失败");
        }
        return ResponseResult.success(HttpStatusEnum.SUCCESS_RESPONSE);
    }

    /**
     * 修改一个商品（管理员）
     *
     * @param updateRequest
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('system:user:list')")
    public ResponseResult<Boolean> updateGoodsTypeById(@RequestBody @Validated GoodsUpdateRequest updateRequest) {
        // 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long id = loginUser.getUser().getId();

        // 构造默认的标签和图片
        String[] tags = new String[]{"其他"};
        String[] images = new String[]{"https://ts2.cn.mm.bing.net/th?id=OIP-C.2TG_Vyb9szQcGK84NVDyLgHaHa&w=249&h=250&c=8&rs=1&qlt=90&o=6&dpr=1.3&pid=3.1&rm=2"};

        Goods goods = new Goods();
        BeanUtils.copyProperties(updateRequest,goods);
        goods.setTags(Optional.ofNullable(updateRequest.getTags()).orElse(JSONUtil.toJsonStr(tags)));
        goods.setImages(Optional.ofNullable(updateRequest.getImages()).orElse(JSONUtil.toJsonStr(images)));
        goods.setUpdateBy(id);
        goods.setUpdateTime(LocalDateTime.now());

        boolean b = goodsService.updateById(goods);
        if (!b){
            return ResponseResult.error(400,"修改失败");
        }
        return ResponseResult.success(HttpStatusEnum.SUCCESS_RESPONSE);
    }

    /**
     * 查询商品列表 （管理员）
     *
     * @param goodsQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @PreAuthorize("hasAuthority('system:user:list')")
    public ResponseResult<Page<Goods>> listGoodsByPage(@RequestBody GoodsQueryRequest goodsQueryRequest) {
        long current = goodsQueryRequest.getCurrent();
        long size = goodsQueryRequest.getPageSize();
        Page<Goods> goodsTypePage = goodsService.page(new Page<>(current, size),
                goodsService.getQueryWrapper(goodsQueryRequest));
        return ResponseResult.success(HttpStatusEnum.SUCCESS_RESPONSE, goodsTypePage);
    }

    /**
     * 查询商品分类列表
     *
     * @param goodsQueryRequest
     * @return
     */
    @PostMapping("/listVO/page")
    public ResponseResult<Page<GoodsVO>> listGoodsTypeVOByPage(@RequestBody GoodsQueryRequest goodsQueryRequest) {
        ResponseResult<Page<Goods>> pageResponseResult = listGoodsByPage(goodsQueryRequest);
        Page<Goods> data = pageResponseResult.getData();
        List<Goods> records = data.getRecords();
        List<GoodsVO> collect = records.stream().map(GoodsVO::objToVo).collect(Collectors.toList());

        long current = goodsQueryRequest.getCurrent();
        long size = goodsQueryRequest.getPageSize();
        Page<GoodsVO> goodsTypeVOPage = new Page<>();
        goodsTypeVOPage.setCurrent(current);
        goodsTypeVOPage.setSize(size);
        goodsTypeVOPage.setRecords(collect);
        return ResponseResult.success(HttpStatusEnum.SUCCESS_RESPONSE, goodsTypeVOPage);
    }
}
